//-----------------------------------------------------------------------

// <copyright file="IntegerFieldDefinition.cs" company="Jamie Knight">

// Copyright (c) Jamie Knight. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

using System;
using System.Windows.Controls;
using System.Windows.Data;

namespace DevKnightlie.WPF.AutoForm.FieldDefinitions
{
    /// <summary>
    /// validation rul which checks that input is a valid integer
    /// </summary>
    public class IntegerValidationRule : ValidationRule
    {

        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            bool isValid = false;
            int i = 0;
            isValid = int.TryParse(value as String, out i);
            return new ValidationResult(isValid, null);
        }
    }

    /// <summary>
    /// Field Definition which creates a TextBox whose input must be a valid integer
    /// </summary>
    public class IntegerFieldDefinition: BaseFieldDefinition
    {


        #region Methods

        public override void BuildInputControl()
        {
            TextBox integerTextBox = new TextBox()
            {
                TextAlignment = System.Windows.TextAlignment.Right,
                VerticalContentAlignment = System.Windows.VerticalAlignment.Center
            };
            Binding integerBinding = new Binding(PropertyName);
            integerBinding.ValidationRules.Add(new IntegerValidationRule());
            BindingOperations.SetBinding(integerTextBox, TextBox.TextProperty, integerBinding);
            SetupEnabledBinding(integerTextBox);
            ContainerControl = InputControl = integerTextBox;
        }


        #endregion

    }
}
